package com.qf.controller;

import com.qf.pojo.SysUsers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 提交登录表单
 * @author lixu
 */
@Controller
public class LoginController {

    /**
     * 登录
     * Boolean rememberMe == null  参数转换异常
     */
    @RequestMapping("/doLogin1")
    public String doLogin(String username, String password, Boolean rememberMe, Model model){
        //1:判断用户名或密码不能空或NULL
        //2:登录
        Subject subject = SecurityUtils.getSubject();

        //加密
        Md5Hash md5Hash = new Md5Hash(password,username,1024);


        //开始登录
        UsernamePasswordToken usernamePasswordToken =
                new UsernamePasswordToken(username,md5Hash.toString());
        //判断是否需要记住我
        if(null != rememberMe){
            // false不用记住或是true记住我
            usernamePasswordToken.setRememberMe(rememberMe);
        }
        try {
            subject.login(usernamePasswordToken);//Login背后校验用户名密码是 Realm realm = new MyRealm
            System.out.println("登录成功了");


            //System.out.println(subject.isAuthenticated());

           // SysUsers sysUsers = (SysUsers) subject.getPrincipal();


           // System.out.println(subject.hasRole("管理员")?"是管理员":"不是管理员");
            //subject.isPermitted("sys:user:*")

            //Session session = subject.getSession();
            //跳转首页
            return "/index.jsp";
        } catch (AuthenticationException e) {
            //System.out.println("登录失败了");
            model.addAttribute("error",e.getMessage());
        }
        return "/login.jsp";

    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public @ResponseBody Map logout(){

        Subject subject = SecurityUtils.getSubject();
        //清理Session
        subject.logout();

        Map result = new HashMap<>();
        result.put("code",0);
        return result;//"{’code‘:0}"
    }
}
